const Koa = require('koa');
const app = new Koa();

const KoaRouter = require('koa-router');
const router = new KoaRouter();

const { query } = require('./utility/mysql');

// 查询 R => read
router.get('/users', async (ctx) => {
    ctx.body = '获取用户列表';
    // get 请求，从 ctx.query 中接收
    let { pagenum, pagesize } = ctx.query;
    pagenum = pagenum || 1;
    pagesize = pagesize || 10;

    console.log({ pagenum, pagesize });
    // 分页算法
    const startIndex = (pagenum - 1) * pagesize;
    if (isNaN(pagesize)) {
        ctx.body = {
            code: 400,
            message: '参数有误',
        };
        return;
    }
    let res = await query('select id, username from user limit ?, ?', [
        startIndex,
        parseInt(pagesize),
    ]);

    const [{ count: total }] = await query(
        'select count(*) as count from user',
    );
    console.log();

    ctx.body = {
        code: 200,
        data: {
            total,
            list: res,
        },
        message: '请求成功',
    };
});

// 添加用户 C => create
router.post('/users', async (ctx) => {
    // 结构参数
    const { username, password } = ctx.request.body;
    // console.log({ username, password });
    // 用户唯一性校验
    let res = await query(
        'select username, password from user where username = ?',
        [username],
    );
    // console.log(res);
    if (res.length !== 0) {
        ctx.body = {
            code: 403,
            message: '用户已存在',
        };
        return;
    }
    // 执行添加操作
    res = await query('insert into user (username, password) values (?, ?)', [
        username,
        password,
    ]);
    /**
     * {
        fieldCount: 0,
        affectedRows: 1,
        insertId: 8,
        serverStatus: 2,
        warningCount: 0,
        message: '',
        protocol41: true,
        changedRows: 0
    }
    */
    console.log(res);
    if (res.affectedRows === 0) {
        ctx.body = {
            code: 500,
            message: '插入失败',
        };
        return;
    }
    // 添加成功
    ctx.body = {
        code: 201,
        data: {
            newId: res.insertId,
        },
        message: '用户添加成功',
    };
});

// 修改 U => update
// :id 叫做 路径参数
router.put('/users/:id', async (ctx) => {
    ctx.body = '修改用户信息';
    // 路径参数的获取方式
    const { id } = ctx.params;
    const { password } = ctx.request.body;
    console.log({ id, password });
    // 连接数据，修改用户密码
    let res = await query('update user set password = ? where id = ?', [
        password,
        id,
    ]);
    console.log(res);
    /**
     * {
        fieldCount: 0,
        affectedRows: 1,
        insertId: 0,
        serverStatus: 2,
        warningCount: 0,
        message: '(Rows matched: 1  Changed: 1  Warnings: 0',
        protocol41: true,
        changedRows: 1
    }
    */
    if (res.affectedRows === 1) {
        ctx.body = {
            code: 200,
            message: '修改成功',
        };
        return;
    }
});

// 删除 D => delete
router.delete('/users/:id', async (ctx) => {
    // ctx.body = '删除用户';
    const { id } = ctx.params;
    let res = await query('delete from user where id = ?', [id]);
    console.log(res);
    /**
     * {
        fieldCount: 0,
        affectedRows: 1,
        insertId: 0,
        serverStatus: 2,
        warningCount: 0,
        message: '',
        protocol41: true,
        changedRows: 0
        }
    */
    if (res.affectedRows === 1) {
        ctx.body = {
            code: 200,
            message: '删除成功',
        };
        return;
    }

    ctx.body = {
        code: 404,
        message: '用户不存在',
    };
});

const bodyparser = require('koa-bodyparser');

app.use(bodyparser());

// 加载路由时，一定要也在 bodyParser 中间件的后面
app.use(router.routes());

app.listen(3000, () => {
    console.log('启动了');
});
